package io.persimmon.core.util.lambda;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LambdaPropertyParser {

    private static final Map<Serializable, String> CACHE = new ConcurrentHashMap<>();

    /**
     * 解析Lambda表达式获取属性名
     *
     * @param lambda Lambda表达式
     * @return 属性名
     */
    public static String parse(Serializable lambda) {
        return CACHE.computeIfAbsent(lambda, l -> {
            try {
                Method writeReplace = l.getClass().getDeclaredMethod("writeReplace");
                writeReplace.setAccessible(true);
                SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(l);
                String methodName = serializedLambda.getImplMethodName();

                // 转换为属性名（如：getName → name）
                return convertToPropertyName(methodName);
            } catch (Exception e) {
                throw new RuntimeException("Failed to parse lambda property", e);
            }
        });
    }

    private static String convertToPropertyName(String methodName) {
        if (methodName.startsWith("get")) {
            return decapitalize(methodName.substring(3));
        } else if (methodName.startsWith("is")) {
            return decapitalize(methodName.substring(2));
        }
        throw new IllegalArgumentException("Invalid getter method: " + methodName);
    }

    private static String decapitalize(String str) {
        return str.isEmpty() ? str : str.substring(0, 1).toLowerCase() + str.substring(1);
    }
}